package com.csii.activiti.server.core.listener.base;

import com.csii.activiti.server.core.constant.CommonConstant;
import com.csii.activiti.server.core.entity.ActFlowData;
import com.csii.activiti.server.core.entity.ActFlowNode;
import com.csii.activiti.server.core.mapper.ActFlowNodeMapper;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Map;

public abstract class BaseServiceNodeExecutor implements JavaDelegate, Serializable {

    @Autowired
    private ActFlowNodeMapper actFlowNodeMapper;

    @Override
    public void execute(DelegateExecution execution) {
        if (execution instanceof ExecutionEntityImpl){
            ExecutionEntityImpl executionEntity = (ExecutionEntityImpl) execution;
            String activityId = executionEntity.getActivityId();
            //获取节点数据
            ActFlowNode actFlowNode = actFlowNodeMapper.selectById(activityId).transitionActFlowNode();
            //自定义扩展数据
            Map<String, Object> customData = actFlowNode.getServiceNodeConfiguration().getCustomData();
            //获取表单数据
            //runtimeService.getVariable(executionEntity)
            ExecutionEntityImpl parentExecutionEntity = executionEntity.getParent();
            Map<String, Object> formData = (Map<String, Object>) parentExecutionEntity.getVariableInstance(CommonConstant.FORM_DATA).getValue();

            ActFlowData flowData = new ActFlowData();
            flowData.setInitiator(parentExecutionEntity.getStartUserId());
            flowData.setProcessName(parentExecutionEntity.getProcessDefinitionName());
            flowData.setProcessDefinitionId(parentExecutionEntity.getProcessDefinitionId());
            flowData.setProcessKey(parentExecutionEntity.getProcessDefinitionKey());
            flowData.setProcessInstanceId(parentExecutionEntity.getProcessInstanceId());

            executeService(actFlowNode,customData,formData,flowData);
        }
    }
    /**
     *  当前服务节点描述
     * @return
     */
    public abstract String serviceNodeDescription();

    /**
     *  是否在服务节点列表展示
     * @return
     */
    public boolean isShowList(){
        return true;
    }

    /**
     *  beanName默认为null以当前类名为准
     * @return
     */
    public String beanName(){
        return null;
    }

    /**
     *  执行方法
     * @return
     */
    public abstract void executeService(ActFlowNode actFlowNode, Map<String, Object> customData,Map<String, Object> formData,ActFlowData flowData);


}
